package com.yeban.javase.day19;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

/**
 * @Desc 客户端
 * @Author yeban
 * @Date 2025/11/3
 *
 *
 */
public class TCPClient {

    public static void main(String[] args) throws IOException {
        System.out.println("---------- TCPClient ----------");
        Scanner sc = new Scanner(System.in);
        Socket socket = null;
        PrintWriter pw = null;
        BufferedReader br = null;

        try {
            // 创建Socket：第一个参数：192.168.0.108，第二个参数：端口号
            socket = new Socket("192.168.0.108",8123);
            System.out.println("客户端正常启动！");

            while(true) {
                // 客户端每次输入的信息
                String str = sc.nextLine();
                // 写消息
                pw = new PrintWriter(socket.getOutputStream());
                pw.println(str);
                pw.flush();
                // 客户端应该在写出消息后，进行关闭
                if(str.equals("exit")) {
                    break;
                }
                // 读消息
                br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                String s = br.readLine();
                System.out.println("客户端接收到信息：" + s);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if(br != null) {
                br.close();
            }
            if(pw != null) {
                pw.close();
            }
            if(socket != null) {
                socket.close();
            }
        }

    }
}
